package com.strongbj.iot.devices.dam.sub.dacai.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessage;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessageType;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnEntity;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 打开超级(仙人)模式
 * 
 * @author yuzhantao
 *
 */
public class OpenXModeHandle implements IMessageHandle<DaCaiMessage, Object> {
	private static Logger logger = LogManager.getLogger(OpenXModeHandle.class.getName());
	protected final static String COMMAND_CODE = "B111"; // 打开页面命令的编号
	protected final static byte TO_SCREEN_COMMAND = (byte) 0xFF; // 传递到屏幕的命令编码
	protected final static String DEFAULT_DEVICE_CODE = "000000"; // 设备默认编号
	protected final static byte[] OPEN_X_MODE_DATAS = { (byte) 0xEE, (byte) 0xB1, (byte) 0x00, (byte) 0x00, (byte) 0x07,
			(byte) 0xFF, (byte) 0xFC, (byte) 0xFF, (byte) 0xFF }; // 空参数
	protected DAMMessageFactory damMessageFactory = new DAMMessageFactory();

	private int curIndex;
//	private int[] clickSpanTime = { -500, -500, 1000, 1000 };
	@SuppressWarnings("unused")
	private long prevTime;

	@Override
	public boolean isHandle(DaCaiMessage t) {
		if (t.getMessageType() == DaCaiMessageType.System && t.getCommand().equals(COMMAND_CODE)) {
			ScreenReturnEntity sr = ScreenReturnFactory.create(t.getDatas());
			// 如果点击触发的控件类型为按钮，屏幕id为0，按钮id为6，就认为是打开传感器设置界面
			if (sr.getControlType() == 16 && sr.getScreenId() == 0 && sr.getControlId() == 999)
				return true;
		}
		return false;
	}

	private void clearDatas() {
		this.curIndex = 0;
		this.prevTime = 0;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DaCaiMessage t) {
		System.out.println(this.curIndex);
//		if (this.curIndex > this.clickSpanTime.length - 1
//				|| (System.currentTimeMillis() - this.prevTime)*(clickSpanTime[this.curIndex]/Math.abs(clickSpanTime[this.curIndex])) < clickSpanTime[this.curIndex]) {
//			this.clearDatas();
//		} else {
//			this.curIndex++;
//		}
//		this.prevTime=System.currentTimeMillis();
//		
//		if (curIndex != this.clickSpanTime.length)
//			return null;
		this.curIndex++;
		if(this.curIndex<5) return null;

		Channel channel = ctx.channel();
		ITaskManager taskManager = DAMManager.getTaskManager(t.getDamCode());
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				if (channel != null && channel.isActive()) {
					// 发送获取DAM传感器参数的命令到DAM
					sendOpenXModeMessage(channel);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					logger.error("主机没有找到指定channel");
				}
			}
		});

		this.clearDatas();
		return null;
	}

	/**
	 * 发送打开X模式窗口消息
	 * 
	 * @param channel
	 */
	private void sendOpenXModeMessage(Channel channel) {
		final byte[] datas = message2Bytes(DEFAULT_DEVICE_CODE, TO_SCREEN_COMMAND, OPEN_X_MODE_DATAS);
		ByteBuf bs = Unpooled.copiedBuffer(datas);
		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("DAM自动下发打开仙人模式命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("DAM自动下发打开仙人模式命令失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	/**
	 * 获取传感器命令转byte数组
	 * 
	 * @param np
	 * @return
	 */
	private byte[] message2Bytes(String deviceCode, byte command, byte[] datas) {
		// 创建设置目标服务器的指令
		byte[] retDatas = damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()),
				deviceCode, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				command, // 命令
				datas // 数据
		); // 通过dam消息工厂获取指令
		return retDatas;
	}
}
